/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.edu.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.cache.CacheUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.edu.entity.EduSubject;
import com.jeesite.modules.edu.service.EduSubjectService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.utils.UserUtils;

/**
 * edu_subjectController
 * @author 赵俊飞
 * @version 2019-03-02
 */
@Controller
@RequestMapping(value = "${adminPath}/edu/eduSubject")
public class EduSubjectController extends BaseController {

	@Autowired
	private EduSubjectService eduSubjectService;
	@Autowired
	private EmployeeService employeeService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public EduSubject get(String dictCode, boolean isNewRecord) {
		return eduSubjectService.get(dictCode, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("edu:eduSubject:view")
	@RequestMapping(value = {"list", ""})
	public String list(EduSubject eduSubject, Model model) {
		model.addAttribute("eduSubject", eduSubject);
		return "modules/edu/eduSubjectList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("edu:eduSubject:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<EduSubject> listData(EduSubject eduSubject) {
		if (StringUtils.isBlank(eduSubject.getParentCode())) {
			eduSubject.setParentCode(EduSubject.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(eduSubject.getDictCode())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getDictLabel())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getDictValue())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getDictType())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getIsSys())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getDescription())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getCssStyle())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getCssClass())){
			eduSubject.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduSubject.getRemarks())){
			eduSubject.setParentCode(null);
		}
		List<EduSubject> list = eduSubjectService.findList(eduSubject);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("edu:eduSubject:view")
	@RequestMapping(value = "form")
	public String form(EduSubject eduSubject, Model model) {
		// 创建并初始化下一个节点信息
		eduSubject = createNextNode(eduSubject);
		model.addAttribute("eduSubject", eduSubject);
		return "modules/edu/eduSubjectForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public EduSubject createNextNode(EduSubject eduSubject) {
		if (StringUtils.isNotBlank(eduSubject.getParentCode())){
			eduSubject.setParent(eduSubjectService.get(eduSubject.getParentCode()));
		}
		if (eduSubject.getIsNewRecord()) {
			EduSubject where = new EduSubject();
			where.setParentCode(eduSubject.getParentCode());
			EduSubject last = eduSubjectService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				eduSubject.setTreeSort(last.getTreeSort() + 30);
				eduSubject.setDictCode(IdGen.nextCode(last.getDictCode()));
			}else if (eduSubject.getParent() != null){
				eduSubject.setDictCode(eduSubject.getParent().getDictCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (eduSubject.getTreeSort() == null){
			eduSubject.setTreeSort(EduSubject.DEFAULT_TREE_SORT);
		}
		return eduSubject;
	}

	/**
	 * 保存edu_subject
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated EduSubject eduSubject) {
		eduSubjectService.save(eduSubject);
		return renderResult(Global.TRUE, text("保存edu_subject成功！"));
	}
	
	/**
	 * 停用edu_subject
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(EduSubject eduSubject) {
		EduSubject where = new EduSubject();
		where.setStatus(EduSubject.STATUS_NORMAL);
		where.setParentCodes("," + eduSubject.getId() + ",");
		long count = eduSubjectService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该edu_subject包含未停用的子edu_subject！"));
		}
		eduSubject.setStatus(EduSubject.STATUS_DISABLE);
		eduSubjectService.updateStatus(eduSubject);
		return renderResult(Global.TRUE, text("停用edu_subject成功"));
	}
	
	/**
	 * 启用edu_subject
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(EduSubject eduSubject) {
		eduSubject.setStatus(EduSubject.STATUS_NORMAL);
		eduSubjectService.updateStatus(eduSubject);
		return renderResult(Global.TRUE, text("启用edu_subject成功"));
	}
	
	/**
	 * 删除edu_subject
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(EduSubject eduSubject) {
		eduSubjectService.delete(eduSubject);
		return renderResult(Global.TRUE, text("删除edu_subject成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("edu:eduSubject:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(EduSubject eduSubject,String excludeCode, String isShowCode,String self) {
		if (!org.springframework.util.StringUtils.isEmpty(self) && self.equals("true")) {
			User user = UserUtils.getUser();
			if(!user.isAdmin()) {
				List<Role> roles = user.getRoleList();
				logger.info("roles:{}",roles.size());
				for(Role role : roles) {
					if(role.getRoleCode().equals("teacher")||role.getRoleCode().equals("admin")) {
						Employee employee = employeeService.get(user.getUserCode());
						Office office = employee.getOffice();
						if(!org.springframework.util.StringUtils.isEmpty(office)) {
							Extend ext = office.getExtend();
							if(!org.springframework.util.StringUtils.isEmpty(ext)) {
								String education = ext.getExtendS3();
								if (!org.springframework.util.StringUtils.isEmpty(education)) {
									eduSubject.setDictType("edu_gaozhi");
									if(education.equals("本科")) {
										eduSubject.setDictType("edu_benke");
									}
								}
							}
						}
					}
				}
			}
		}
		String key = eduSubject.getDictType();
		if(org.springframework.util.StringUtils.isEmpty(key)) {
			key = "ALL";
		}
		List<Map<String, Object>> mapList = CacheUtils.get("CACHE_EDU_SUBJECT_".concat(key));
		
		if(!CollectionUtils.isEmpty(mapList)) {
			return mapList;
		}
		mapList = ListUtils.newArrayList();
		List<EduSubject> list = eduSubjectService.findList(eduSubject);
		if(!org.springframework.util.StringUtils.isEmpty(eduSubject.getDictType())) {
			eduSubject.setDictType("edu_nothing");
			List<EduSubject> nothingList = eduSubjectService.findList(eduSubject);
			if(!CollectionUtils.isEmpty(nothingList)) {
				list.addAll(nothingList);
			}
		}
		
		
		
		for (int i=0; i<list.size(); i++){
			EduSubject e = list.get(i);
			// 过滤非正常的数据
			if (!EduSubject.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getDictLabel(), e.getDictLabel()));
			mapList.add(map);
		}
		CacheUtils.put("CACHE_EDU_SUBJECT_".concat(key),mapList);
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("edu:eduSubject:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(EduSubject eduSubject){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		eduSubjectService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}